<template>
  <div class="index-map">
    <div ref="chartRef" id="chartBox" class="index-map-chart"></div>
  </div>
</template>

<script setup>
import * as echarts from 'echarts'
import * as sichuanJson from '@/assets/json/sichuan.json'
import { ref, getCurrentInstance, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
echarts.registerMap('sichuan', sichuanJson)
const { proxy } = getCurrentInstance()
const router = useRouter()

const chartRef = ref(null)
let mapChart = null
let faultByHourTime = ref(null);

let seriesData = sichuanJson.features.map((item) => {
  let aq = Math.floor(Math.random() * 101)
  return {
    name: item.properties.name,
    adcode: item.properties.adcode,
    center: item.properties.centroid,
    Installed: parseInt(Math.random() * 1000),
    uninstalled: parseInt(Math.random() * 1000),
    finishing: aq,
    value: aq
  }
})

// 动态计算柱形图的高度
const lineMaxHeight = () => {
  const maxValue = Math.max(...seriesData.map((item) => item.value))
  return 0.5 / maxValue
}

// 柱状体的主干
const lineData = seriesData.map((item) => {
  let coords = [item.center, [item.center[0], item.center[1] + item.value * lineMaxHeight()]]
  return {
    coords,
    name: item.name,
    Installed: item.Installed,
    uninstalled: item.uninstalled,
    finishing: item.finishing
  }
})

// 柱状体的顶部
const scatterTopData = seriesData.map((item) => {
  let coords = [item.center[0], item.center[1] + item.value * lineMaxHeight(), item.value]
  return {
    coords,
    name: item.name,
    Installed: item.Installed,
    uninstalled: item.uninstalled,
    finishing: item.finishing
  }
})

// 柱状体的底部
const scatterBottomData = seriesData.map((item) => {
  return {
    name: item.name,
    value: item.center,
    Installed: item.Installed,
    uninstalled: item.uninstalled,
    finishing: item.finishing
  }
})

const series = [
  {
    name: '地图数据',
    map: 'sichuan',
    type: 'map',
    geoIndex: 0,
    zlevel: 1,
    data: seriesData,
    tooltip: {
      show: true // 确保地图区域显示默认tooltip
    }
  },
  // 柱状体的主干
  {
    type: 'lines',
    zlevel: 5,
    effect: {
      show: false,
      symbolSize: 5 // 图标大小
    },
    lineStyle: {
      width: 14, // 尾迹线条宽度
      color: 'rgb(22,255,255, .6)',
      opacity: 1, // 尾迹线条透明度
      curveness: 0 // 尾迹线条曲直度
    },
    silent: false,
    data: lineData,
    tooltip: {
      show: true
    },

  },
  // 柱状体的顶部
  {
    type: 'scatter',
    coordinateSystem: 'geo',
    geoIndex: 0,
    zlevel: 5,
    label: {
      show: false,
      formatter: function (e) {
        return `数值：${e.data[2]}`
      },
      position: 'top'
    },
    symbol: 'circle',
    symbolSize: [20, 10],
    itemStyle: {
      color: 'rgb(22,255,255, 1)',
      opacity: 1
    },
    silent: true,
    data: scatterTopData,
    tooltip: { show: false }
  },
  // 柱状体的底部
  {
    type: 'scatter',
    coordinateSystem: 'geo',
    geoIndex: 0,
    zlevel: 4,
    label: {
      show: true,
      color: 'rgba(255,255,255,0.8)',
      fontSize: 10,
      formatter: '{b}',
      position: 'bottom',
      fontSize: 10,
      distance: 10
    },
    symbol: 'circle',
    symbolSize: [14, 6],
    itemStyle: {
      color: '#22EEFC',
      opacity: 1
    },
    silent: false,
    data: scatterBottomData,
    tooltip: {
      show: true
    }
  },
  // 底部外框
  {
    type: 'effectScatter',
    rippleEffect: {
      //涟漪特效相关配置
      period: 4, //动画的周期，秒数，值越小速度越快
      brushType: 'stroke', //波纹的绘制方式，可选 'stroke' 和 'fill'
      scale: 2, //动画中波纹的最大缩放比例，值越大波纹越大 4
      color: 'rgb(34,238,252,0.4)', //涟漪的颜色
      number: 2 //波纹的数量
    },
    coordinateSystem: 'geo',
    geoIndex: 0,
    zlevel: 4,
    label: {
      show: false
    },
    symbol: 'circle',
    symbolSize: [20, 8],
    itemStyle: {
      color: {
        type: 'radial',
        x: 0.5,
        y: 0.5,
        r: 0.5,
        colorStops: [
          {
            offset: 0,
            color: 'rgb(34,238,252, 0)' // 0% 处的颜色
          },
          {
            offset: 0.74,
            color: 'rgb(34,238,252, 0)' // 100% 处的颜色
          },
          {
            offset: 0.75,
            color: 'rgb(34,238,252, 0.16)' // 100% 处的颜色
          },
          {
            offset: 1,
            color: 'rgb(34,238,252, 0.16)' // 100% 处的颜色
          }
        ]
      }
    },
    data: scatterBottomData
  }
]
const visualMap = {
  show: true, // 可以选择是否显示视觉映射组件
  type: 'piecewise', // 连续的
  min: 0,
  max: 100,
  left: '0',
  bottom: '20%',
  calculable: true, // 是否显示手柄
  precision: 0, // 小数点位数
  seriesIndex: [0], // 应用到的系列索引
  textStyle: {
    color: '#FFFFFF', // 设置文本颜色
    fontSize: 12 // 设置文本字体大小
  },
  pieces: [
    { min: 0, max: 19.99, label: '20%', color: '#54473E' },
    { min: 19.99, max: 39.99, label: '40%', color: '#594335' },
    { min: 39.99, max: 59.99, label: '60%', color: '#B0814C' },
    { min: 59.99, max: 79.99, label: '80%', color: '#CC923E' },
    { min: 79.99, label: '100%', color: '#FAC240' }
  ]
}

let option = {
  tooltip: {
    show: true,
    trigger: 'item',
    extraCssText: 'padding: 0;border: none;',
    formatter: function (params) {
      // console.log(333, params);
      let tooltipHtml = `<div class="index-map-tooltip">
                      <div class="index-map-tooltip-title">${params.data.name}</div>
                      <div class="index-map-tooltip-list">
                        <div class="index-map-tooltip-list-key">已安装</div>
                        <div class="index-map-tooltip-list-value">${params.data.Installed}个</div>
                      </div>
                      <div class="index-map-tooltip-list">
                        <div class="index-map-tooltip-list-key">未安装</div>
                        <div class="index-map-tooltip-list-value">${params.data.uninstalled}个</div>
                      </div>
                      <div class="index-map-tooltip-list">
                        <div class="index-map-tooltip-list-key">项目完成率</div>
                        <div class="index-map-tooltip-list-value">${params.data.finishing}%</div>
                      </div>
                    </div>`

      return tooltipHtml
    }
  },
  geo: {
    map: 'sichuan',
    roam: false, // 是否允许缩放和平移
    zoom: 1.2,
    label: {
      show: false,
      color: 'rgba(255,255,255,0.8)',
      fontSize: 10,
      textShadowColor: 'rgba(0,0,0,0.5)',
      textShadowBlur: 4,
      textShadowOffsetX: 0,
      textShadowOffsetY: 1
    },
    itemStyle: {
      borderColor: '#372519',
      borderWidth: 1
    },
    emphasis: {
      itemStyle: {
        areaColor: null, // 或指定与正常状态相同的颜色，这里设置为null意在使用默认或地图json中定义的颜色
        borderColor: null // 同上，去除边框高亮效果
      },
      label: {
        show: false // 隐藏标签
      }
    }
  },
  visualMap: visualMap,
  series: series
}

const resizeHandler = () => {
  mapChart.resize()
}
const renderMap = () => {
  if (!mapChart) {
    mapChart = echarts.init(chartRef.value, null, {
      renderer: 'svg'
    })
  }
  mapChart.dispatchAction({
    type: 'restore'
  })
  mapChart.setOption(option)

  //  轮播
  var faultByHourIndex = 0; //播放所在下标
  function tooltipcart() {
    //使得tootip每隔三秒自动显示
    mapChart.dispatchAction({
      type: 'showTip', // 根据 tooltip 的配置项显示提示框。
      seriesIndex: 0,
      dataIndex: faultByHourIndex,
    });
    mapChart.dispatchAction({
      type: 'highlight', // 高亮显示
      seriesIndex: 0,
      dataIndex: faultByHourIndex,
    });
    mapChart.dispatchAction({
      type: 'downplay', // 取消高亮
      seriesIndex: 0,
      dataIndex:
        faultByHourIndex == 0 ? option.series[0].data.length - 1 : faultByHourIndex - 1,
    });

    faultByHourIndex++;
    if (faultByHourIndex > option.series[0].data.length - 1) {
      faultByHourIndex = 0;
    }
  }

  // 鼠标移入的时候 取消高亮 并且取消定时器
  mapChart.on('mouseover', (params) => {
    mapChart.dispatchAction({
      type: 'downplay', // 取消高亮
      seriesIndex: 0,
      dataIndex:
        faultByHourIndex == 0 ? option.series[0].data.length - 1 : faultByHourIndex - 1,
    });
    clearInterval(faultByHourTime.value);
    faultByHourTime.value = null;
  });

  //鼠标移出继续轮播高亮
  mapChart.on('mouseout', (params) => {
    if (!faultByHourTime.value) faultByHourTime.value = setInterval(tooltipcart, 3000);
  });
  if (!faultByHourTime.value) faultByHourTime.value = setInterval(tooltipcart, 3000);


  mapChart.dispatchAction({ type: 'dataZoom', start: 0, end: 100 })
}
onMounted(() => {
  renderMap()
  window.addEventListener('resize', resizeHandler)
})
onUnmounted(() => {
  window.removeEventListener('resize', resizeHandler)
  clearInterval(faultByHourTime.value);
  faultByHourTime.value = null;
})
</script>

<style lang="scss">
.index-map {
  width: 100%;
  height: 100%;
  display: flex;

  .index-map-chart {
    width: 100%;
    height: 80%;
    // border: 1px solid red;
  }

  .index-map-tooltip {
    display: flex;
    flex-direction: column;
    background: linear-gradient(180deg, #1c1711 0%, #18150f 100%);
    box-shadow: 0px 2px 8px 0px rgba(235, 94, 18, 0.09);
    border-radius: 6px 6px 6px 6px;
    border: 1px solid #dda862;
    padding: 12px 18px;

    .index-map-tooltip-title {
      font-weight: 600;
      font-size: 14px;
      color: #ecf8ff;
      margin-bottom: 4px;
    }

    .index-map-tooltip-list {
      display: flex;
      align-items: baseline;
      justify-content: space-between;
      margin-top: 4px;

      .index-map-tooltip-list-key {
        white-space: nowrap;
        font-size: 12px;
        color: rgba(236, 248, 255, 0.8);
      }

      .index-map-tooltip-list-value {
        white-space: nowrap;
        margin-left: 30px;
        text-align: right;
        font-weight: 600;
        font-size: 12px;
        color: rgba(236, 248, 255, 0.8);
      }
    }
  }
}
</style>
